<template>
    <van-tabs class="ui-navbar" :class="['ui-navbar--' + type]" v-model="active" @input="handleTabsInput" :ellipsis="false">
        <van-tab 
            v-for="(item, index) in data" 
            :name="item[valueField]" 
            :title="item[textField]"
            :key="index"
        >
            <template #title>
                <slot name="item" :item="item" :active="item[valueField] === active" :is-last="index === lastIndex" :is-first="!index">{{item[textField]}}</slot>
            </template>
        </van-tab>
    </van-tabs>
</template>
<script>
import Tabs from 'vant/lib/tabs'
import Tab from 'vant/lib/tab'
import 'vant/lib/tabs/style'
import 'vant/lib/tab/style'

export default {
    name: 'UiNavbar',
    components: {
        VanTabs: Tabs,
        VanTab: Tab
    },
    props: {
        value: {
            type: [String, Number]
        },
        valueField: {
            type: String,
            default: 'value'
        },
        textField: {
            type: String,
            default: 'text'
        },
        data: {
            type: Array,
            default: () => []
        },
        type: {
            type: String,
            default: 'default',
            validator (value) {
                return ['default', 'custom'].indexOf(value) >= 0
            }
        }
    },
    computed: {
        active: {
            get () {
                return this.value
            },
            set (val) {
                this.$emit('input', val)
            }
        },
        lastIndex () {
            return (this.data.length || []) - 1
        }
    },
    methods: {
        handleTabsInput (val) {
            this.$emit('change', {
                value: val,
                item: this.data.find(v => v[this.valueField] === val)
            })
        }
    }
}
</script>
<style lang="scss">
.ui-navbar{
    .van-tabs__content{
        display: none;
    }
}
.ui-navbar--default{
    .van-tabs__nav{
        padding-left: 0;
        padding-right: 0;
    }
    .van-tabs__line{
        background-color: #2881E2;
        padding-left: 4px;
        padding-right: 4px;  
        box-sizing: content-box;
    }
}
.ui-navbar--custom{
    .van-tabs__nav{
        height: auto;
        padding-bottom: 0;
        padding-left: 0;
        padding-right: 0;
    }
    .van-tabs__wrap{
        height: auto;
    }
    .van-tabs__line{
        display: none;
    }
    .van-tab{
        padding: 0;
        &.van-tab--active{
            font-weight: normal;
        }
    }
}
</style>